package com.genesis.yunnanji.utils;

import android.content.Context;
import android.net.ConnectivityManager;

import com.genesis.yunnanji.config.GenesisCacheConfig;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.ex.HttpException;
import org.xutils.http.RequestParams;
import org.xutils.x;

/**
 * Created by Administrator on 2017/10/23.
 */

public class NetWorkUtils {

    /**
     * Post请求
     */
    public static void doCachePost(RequestParams params, final HttpResultListener listener) {
        params.setCacheDirName(GenesisCacheConfig.logdir);
        x.http().post(params, new Callback.CacheCallback<String>() {
                    @Override
                    public boolean onCache(String result) {
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            listener.OnCached(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        return !isNetworkConnections();
                    }

                    @Override
                    public void onSuccess(String result) {
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            listener.onSuccess(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        // 请求成功后，返回结果
                    }


                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        // 请求失败后返回结果
                        if (!isNetworkConnections() || ex instanceof HttpException) {
                            // 网络错误
                        } else {
                            // 其他请求错误
                        }

                    }


                    @Override
                    public void onCancelled(CancelledException cex) {
                        // 中断请求
                    }

                    @Override
                    public void onFinished() {
                        onFinished();
                        // 请求结束（必调用）
                    }
                }
        );

    }

    public static void doCacheGet(RequestParams params, final HttpResultListener listener) {
        params.setCacheDirName(GenesisCacheConfig.logdir);
        params.setCacheMaxAge(1000 * 60);
        x.http().get(params, new Callback.CacheCallback<String>() {
            @Override
            public boolean onCache(String result) {

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    listener.OnCached(jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return !isNetworkConnections();
            }

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    listener.onSuccess(jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // 请求失败后返回结果
                if (!isNetworkConnections() || ex instanceof HttpException) {
                    // 网络错误
                } else {
                    // 其他请求错误
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                listener.onFinished();
            }

        });
    }


    public interface HttpResultListener {
        /**
         *
         */
        void onSuccess(JSONObject jsonObject);

        void OnCached(JSONObject jsonObject);

        void onFinished();

        void onError(String errorStr);
    }

    /**
     * @return 网络是否连接 true:有网络，false：无网络
     */

    private static boolean isNetworkConnections() {
        ConnectivityManager con = (ConnectivityManager) x.app().getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
        boolean internet = con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
        return (wifi || internet);
    }
}
